package com.flca.frw.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.flca.frw.IEntity;

public class EntityBaseHelper {

	protected List<MergeDto> toMerge = new ArrayList<MergeDto>();
	protected List<IEntity> toAdd = new ArrayList<IEntity>();
	protected List<Long> toDel = new ArrayList<Long>();
	
	/**
	 * This will the three list from above
	 * @param aTargetSet
	 * @param aSourceSet
	 */
	protected void fillLists(Set<?> aTargetSet, Set<?> aSourceSet) 
	{
		toMerge.clear();
		toAdd.clear();
		toDel.clear();
		
		// first fill toMerge with the target objects
		for (Object obj : aTargetSet) {
			IEntity trg = (IEntity) obj;
			toMerge.add(new MergeDto(trg, null));
		}
		
		//now try match these with source objects
		for (Object srcobj : aSourceSet) {
			IEntity src = (IEntity) srcobj;

			for (MergeDto mrgobj : toMerge) {
				if (mrgobj.target.getId() != null && mrgobj.target.getId().equals(src.getId())) {
					mrgobj.source = src; 
					break;
				}
				// if we cant match then
				toAdd.add(src);
			}
		}

		//finally fill the toDel with the leftovers 
		for (MergeDto mrgobj : toMerge) {
			if (mrgobj.source == null) {
				toDel.add((Long) mrgobj.target.getId());  
			}
		}
	}
	
	protected class MergeDto {
		public IEntity source;
		public IEntity target;
		
		MergeDto(IEntity aTarget, IEntity aSource) {
			source = aSource;
			target = aTarget;
		}
	}
}
